import mqtt from 'mqtt';

let client = null;

export function connectMqtt(options) {
	return new Promise((resolve, reject) => {
		// #ifdef H5
		client = mqtt.connect('ws://47.117.131.69:5275/mqtt', options);
		// #endif
		// #ifdef MP-WEIXIN||APP-PLUS
		client = mqtt.connect('wx://47.117.131.69:5275/mqtt', options);
		// #endif


		client.on('connect', () => {
			//console.log('Connected to MQTT server');
			resolve(client);
		});

		client.on('error', (err) => {
			console.error('MQTT connection error:', err);
			reject(err);
		});
	});
}

export function publishMessage(topic, message) {
	if (client) {
		client.publish(topic, message, {}, (err) => {
			if (err) {
				console.error('Message publish error:', err);
			} else {
				console.log('Message published');
			}
		});
	} else {
		console.error('MQTT client is not connected');
	}
}

export function subscribeTopic(topic, messageHandler) {
  if (client) {
    client.subscribe(topic, (err) => {
      if (err) {
        console.error('Subscription error:', err);
      } else {
        console.log(`Subscribed to topic: ${topic}`);
        client.on('message', (topic, message) => {
			 const decoder = new TextDecoder('utf-8');
          if (messageHandler) {
            messageHandler(topic, decoder.decode(message));
          }
        });
      }
    });
  } else {
    console.error('MQTT client is not connected');
  }
}

export function disconnectMqtt() {
  if (client) {
    client.end();
    client = null;
    console.log('MQTT client disconnected');
  } else {
    console.error('MQTT client is not connected');
  }
}